<?php
declare (strict_types=1);

namespace app\middleware;

use app\Request;
use app\service\admin\AdminUserService;
use app\service\utils\TokenService;


class Auth
{

    /**
     * 认证中间件
     * @param $request
     * @param \Closure $next
     * @return mixed|\think\response\Json
     */
    public function handle(Request $request, \Closure $next)
    {
        try {
            $token = $request->header('Authorization');
            $test = $request->param('test');
            if (empty($token) && $test != 'justdoit') {
                throw new \Exception('请重新登录', -1);
            }
            if ($test == 'justdoit') {
                $userId = 2;
            } else {
                $result = (new TokenService())->checkToken($token);
                if ($result->exp < time()) {
                    throw new \Exception('请重新登录', -1);
                }
                $tokenInfo = $result->data;
                $userId = $tokenInfo->id;
            }

            $userService = new AdminUserService();
            $userInfo = $userService->getOneLineById($userId);
//            if ($tokenInfo->username != $userInfo['username']) {
//                throw new \Exception('请重新登录', -1);
//            }
            $request->withMiddleware(['userId' => $userInfo['id']]);
            $request->withMiddleware(['userInfo' => $userInfo]);
        } catch (\Exception $exception) {
            return json()->data(['code' => $exception->getCode(), 'msg' => $exception->getMessage(), 'data' => []]);
        }
        return $next($request);
    }
}
